package com.dingreading.cloud.soms.service.impl;

import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.AccountUtil;
import com.dingreading.cloud.common.util.DateUtil;
import com.dingreading.cloud.common.util.PageDto;
import com.dingreading.cloud.common.util.PageUtil;
import com.dingreading.cloud.soms.dto.CaLessonEvaluateDto;
import com.dingreading.cloud.soms.entity.CaCallNames;
import com.dingreading.cloud.soms.entity.CaLessonEvaluate;
import com.dingreading.cloud.soms.entity.Staff;
import com.dingreading.cloud.soms.entity.StaffRoles;
import com.dingreading.cloud.soms.entity.table.CaLessonEvaluateTableDef;
import com.dingreading.cloud.soms.mapper.CaLessonEvaluateMapper;
import com.dingreading.cloud.soms.service.CaCallNamesService;
import com.dingreading.cloud.soms.service.CaLessonEvaluateService;
import com.dingreading.cloud.soms.service.StaffRolesService;
import com.dingreading.cloud.soms.service.StaffService;
import com.dingreading.cloud.soms.util.CaLessonEvaluateUtils;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;

import static com.dingreading.cloud.soms.entity.table.MembersTableDef.members;

/**
 * 课后评价表 服务层实现。
 *
 * @author EDY
 * @since 2025-11-04
 */
@Service
public class CaLessonEvaluateServiceImpl extends BaseServiceImpl<CaLessonEvaluateMapper, CaLessonEvaluate, CaLessonEvaluateTableDef> implements CaLessonEvaluateService {

    @Resource
    private StaffService staffService;
    @Resource
    private StaffRolesService staffRolesService;
    @Resource
    private CaCallNamesService caCallNamesService;

    @Override
    protected CaLessonEvaluateTableDef getTable() {
        return CaLessonEvaluateTableDef.caLessonEvaluate;
    }

    @Override
    public R<Object> pageList(
            PageUtil pageUtil, String corpUid, String storeUid, String staffUid, String staffName,
            String keyword, String projectUid, String beginDate, String endDate
    ) {
        if (StringUtils.isBlank(corpUid) || StringUtils.isBlank(storeUid) || StringUtils.isBlank(staffUid))
            return R.fail("门店员工字段缺少请检查！");

        Staff staff = staffService.getByStaffUid(corpUid, staffUid);
        if (staff == null)
            return R.fail("未查询到账号！");
        StaffRoles staffRole = staffRolesService.getStoreUidAndStaffUid(storeUid, staffUid);
        if (null == staffRole || StringUtils.isBlank(staffRole.getRoles()))
            return R.fail("员工角色权限获取失败");

        QueryCondition condition = QueryCondition.createEmpty()
                .and(table.agencyUid.eq(corpUid))
                .and(table.storeUid.eq(storeUid));
        if (StringUtils.isNotBlank(keyword))
            condition.and(table.teacherName.like(keyword)
                                  .or(members.memberName.like(keyword)));
        if (StringUtils.isNotBlank(projectUid))
            condition.and(table.projectUid.eq(projectUid));
        if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate))
            condition.and(table.teachDate.between(beginDate, endDate));

        if (!AccountUtil.isStoreManager(staffRole.getRoles())) {
            condition.and(table.teacherUid.eq(staffUid));
        }

        QueryWrapper wrapper = QueryWrapper.create()
                .leftJoin(members).on(table.studentUid.eq(members.uid))
                .where(condition)
                .orderBy(table.id.desc());
        Page<CaLessonEvaluateDto> evaluatePage = getMapper().paginateAs(Page.of(pageUtil.getPage(), pageUtil.getRows()), wrapper, CaLessonEvaluateDto.class);
        PageDto<CaLessonEvaluateDto> caLessonEvaluatePageDto = new PageDto<>();
        caLessonEvaluatePageDto.setTotal(evaluatePage.getTotalRow());
        caLessonEvaluatePageDto.setList(evaluatePage.getRecords());
        return R.ok(caLessonEvaluatePageDto);
    }

    @Override
    public R<Object> getBean(String corpUid, String storeUid, String staffUid, String staffName, String callNamesUid) {
        if (StringUtils.isBlank(corpUid) || StringUtils.isBlank(storeUid) || StringUtils.isBlank(staffUid))
            return R.fail("门店员工字段缺少请检查！");
        if (StringUtils.isBlank(callNamesUid))
            return R.fail("上课记录uid缺少请检查！");

        QueryCondition condition = QueryCondition.createEmpty()
                .and(table.agencyUid.eq(corpUid))
                .and(table.storeUid.eq(storeUid))
                .and(table.callNamesUid.eq(callNamesUid));
        QueryWrapper wrapper = QueryWrapper.create()
                .where(condition);
        CaLessonEvaluateDto caLessonEvaluateDto = getMapper().selectOneByQueryAs(wrapper, CaLessonEvaluateDto.class);
        return R.ok(caLessonEvaluateDto);
    }

    @Override
    public R<Object> teacherEvaluate(
            String corpUid, String storeUid, String staffUid, String staffName,
            String callNamesUid, Integer teacherScore, String teacherComment
    ) throws ParseException {
        if (StringUtils.isBlank(corpUid) || StringUtils.isBlank(storeUid) || StringUtils.isBlank(staffUid))
            return R.fail("门店员工字段缺少请检查！");
        if (StringUtils.isBlank(callNamesUid))
            return R.fail("上课记录uid缺少请检查！");
        if (teacherScore == null || teacherScore < 0 || teacherScore > 5)
            return R.fail("老师评分请填写1-5分！");

        Staff staff = staffService.getByStaffUid(corpUid, staffUid);
        if (staff == null)
            return R.fail("未查询到账号！");
        StaffRoles staffRole = staffRolesService.getStoreUidAndStaffUid(storeUid, staffUid);
        if (null == staffRole || StringUtils.isBlank(staffRole.getRoles()))
            return R.fail("员工角色权限获取失败");


        CaCallNames caCallNames = caCallNamesService.getByCallNamesUid(corpUid, storeUid, callNamesUid);
        if (caCallNames == null)
            return R.fail("未查询到该上课记录！");
        if (caCallNames.getStatus() != 2)
            return R.fail("该课程未完结，不能评价");
        if (StringUtils.isBlank(caCallNames.getTeacherUid()))
            return R.fail("未查询到主讲导读！");

        Date teachDate = DateUtil.parseDate(caCallNames.getTeachDate());
        Date nowDate = DateUtil.parseDate(DateUtil.getNowDateStr(), "yyyy-MM-dd");
        if (nowDate.getTime() < teachDate.getTime())
            return R.fail("活动日期未到：" + caCallNames.getTeachDate() + "，不能评价！");

        if (AccountUtil.isStoreManager(staffRole.getRoles())) {
            // 如果活动时间超过30天不让评价
            long compareDate = DateUtil.differentDays(teachDate, nowDate);
            if (compareDate > 30)
                return R.fail("活动时间已超过30天，不能评价！");
        } else {
            if (!staffUid.equals(caCallNames.getTeacherUid()))
                return R.fail("您不是该课程的主讲导读，不能评价！");

            // 如果活动时间超过5天不让评价
            long compareDate = DateUtil.differentDays(teachDate, nowDate);
            if (compareDate > 5)
                return R.fail("活动时间已超过5天，不能评价！");
        }

        QueryCondition condition = QueryCondition.createEmpty()
                .and(table.agencyUid.eq(corpUid))
                .and(table.storeUid.eq(storeUid))
                .and(table.callNamesUid.eq(callNamesUid));
        CaLessonEvaluate evaluate = getMapper().selectOneByCondition(condition);

        evaluate = CaLessonEvaluateUtils.newBean(caCallNames, evaluate, corpUid, storeUid, staffUid, staffName, teacherScore, teacherComment);
        boolean b = saveOrUpdate(evaluate);
        return b ? R.ok() : R.fail("评价失败！");

    }
}
